import requests
from bs4 import BeautifulSoup
import time
import os
from os import system
import datetime
import sys
from pidModule import writePid

system("title cls") #给终端命名
os.system("mode con cols=128 lines=80")#设置控制台尺寸

# 获取当前脚本所在目录路径
#script_dir = os.path.dirname(os.path.realpath(__file__))

pidPath = "cls.pid"


def getHTMLText(url):
    try:
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'}
        r = requests.get(url, headers=headers,timeout=30)
        r.raise_for_status() # 如果状态不是200，引发HTTPError异常
        # print(r.status_code)# 查看状态码
        r.encoding = r.apparent_encoding
        # print('success')
        return r.text
    except Exception as e:
        print(f"异常信息：{str(e)}")
        return "产生异常"

def getClsList(htmlStr,getNum):
    #获取标题和url
    soup = BeautifulSoup(htmlStr, 'html.parser')
    
    GupiaoList=soup.find_all('div',class_='telegraph-list')
    result=[]
    i = 1
    for gp in GupiaoList:
        #获取的数量
        if i > getNum:
            break

        data={}
        data['title']=gp.text
        #data['url']=gp['href']
        result.append(data)
        content_text = ''
        gupiao_text = ''

        try:
            #输出内容
            content_text = gp.find(class_="telegraph-content-box").getText()
            if str(gp).find('<span class="c-de0422">') != -1:
                #找到了标红的标题
                content_text = "\033[1;31m"+"※"+"\033[0m"+content_text+'\n'
            
            #输出提示的股票
            gupiao_text = gp.find(class_="telegraph-stock-plate-box").getText()
            
        except Exception as e:
            error=e
            #print(f"异常信息：{str(e)}")
            

        if content_text != '':
            print(content_text)
        if gupiao_text != '':
            print("【 "+gupiao_text+" 】")
        if content_text != '' or gupiao_text != '':
            print('') 
            i+=1

        
        #print(data)
    return result


def main():
    os.system("cls")   # 清屏操作
    url =f'https://www.cls.cn/telegraph'
    print("当前时间："+ str(datetime.datetime.now())) 
    print(url)
    print('')
    html=getHTMLText(url)
    ClsInfo=getClsList(html,8)
    
    #print(ClsInfo)
        
if __name__ == '__main__':
    
    #写入进程pid
    writePid(pidPath)

    while True:
        main()
        time.sleep(30)
    


